package lib

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go-micro/framework/gin_"
	"go-micro/src/Course"
	"go-micro/src/service"
)

func init() {
	course := service.NewCourseServiceImpl()
	gin_.NewServiceBuilder().
		Service(course).
		Endpoint(CourseList_Endpoint(course)).
		RequestFunc(CourseList_Request()).
		Middleware(Check_Middleware()).
		ResponseFunc(CourseList_Response()).
		BuildServer("/courselist", "GET")

	gin_.NewServiceBuilder().
		Service(course).
		Endpoint(CourseDetail_Endpoint(course)).
		RequestFunc(CourseDetail_Request()).
		Middleware(Check_Middleware()).
		ResponseFunc(CourseDetail_Response()).
		BuildServer("/coursedetail/:cid", "GET")
}

func Course_Middleware() gin_.Middleware {
	return func(next gin_.Endpoint) gin_.Endpoint {
		return func(context *gin.Context, request interface{}) (response interface{}, err error) {
			fmt.Println("abc")
			return next(context, request)
		}
	}
}

//最终执行业务过程的函数------endpoint，我们叫做 端点
func CourseList_Endpoint(c *service.CourseServiceImpl) gin_.Endpoint {
	return func(context *gin.Context, request interface{}) (response interface{}, err error) {
		resp := &Course.ListResponse{}
		err = c.ListForTop(context, request.(*Course.ListRequest), resp)
		if err != nil {
			return nil, err
		}
		return resp, err
	}
}

//这个函数的作用是怎么处理请求
func CourseList_Request() gin_.EncodeRequestFunc {
	return func(context *gin.Context) (request interface{}, err error) {
		bReq := &Course.ListRequest{}
		return bReq, nil
	}
}

//这个函数作用是：怎么处理响应结果
func CourseList_Response() gin_.DecodeResponseFunc {
	return func(context *gin.Context, response interface{}) error {
		context.JSON(200, response)
		return nil
	}
}

func CourseDetail_Endpoint(c *service.CourseServiceImpl) gin_.Endpoint {
	return func(context *gin.Context, request interface{}) (response interface{}, err error) {
		resp := &Course.DetailResponse{}
		err = c.CourseDetail(context, request.(*Course.CourseDetailRequest), resp)
		return resp, err
	}
}

func CourseDetail_Request() gin_.EncodeRequestFunc {
	return func(context *gin.Context) (request interface{}, err error) {
		bReq := &Course.CourseDetailRequest{}
		err = context.BindUri(bReq)
		err = context.BindHeader(bReq)
		if err != nil {
			return nil, err
		}
		return bReq, nil
	}
}

func CourseDetail_Response() gin_.DecodeResponseFunc {
	return func(context *gin.Context, response interface{}) error {
		context.JSON(200, response)
		return nil
	}
}
